package cn.charmaine.pet.service.impl;

import cn.charmaine.basic.Exception.CustomException;
import cn.charmaine.basic.util.BaiduAuditUtils;
import cn.charmaine.basic.util.CodeGenerateUtils;
import cn.charmaine.basic.util.DistanceUtil;
import cn.charmaine.basic.util.Point;
import cn.charmaine.org.domain.Employee;
import cn.charmaine.org.domain.Shop;
import cn.charmaine.org.domain.User;
import cn.charmaine.org.mapper.ShopMapper;
import cn.charmaine.org.mapper.UserMapper;
import cn.charmaine.pet.domain.OrderPetAcquisition;
import cn.charmaine.pet.domain.Pet;
import cn.charmaine.pet.domain.SearchMasterMsg;
import cn.charmaine.pet.domain.SearchMasterMsgAuditLog;
import cn.charmaine.pet.domain.dto.AcceptDto;
import cn.charmaine.pet.mapper.OrderPetAcquisitionMapper;
import cn.charmaine.pet.mapper.PetMapper;
import cn.charmaine.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.charmaine.pet.mapper.SearchMasterMsgMapper;
import cn.charmaine.pet.service.ISearchMasterMsgService;
import cn.charmaine.basic.base.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xmy
 * @since 2022-07-22
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetMapper petMapper;

    @Override
    public void publish(SearchMasterMsg smm) {
        ////设置寻主消息为待审核状态
        smm.setState(0);
        //寻主消息入库
        searchMasterMsgMapper.insert(smm);
        //查询用户，得到其电话，发送审核消息
        User user = userMapper.selectById(smm.getUserId());
        SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
        //百度ai审核
        if (!BaiduAuditUtils.TextCensor(smm.getName() + smm.getTitle() + smm.getCoatColor() + smm.getAddress())) {
            //审核不通过，不抛异常，发短信给用户提示，保存日志，改变寻主消息状态
            //SmsUtil.sendSms(user.getPhone(),"您发布的消息疑似存在敏感信息，请确认后重试！")
            log.setState(0);//审核不通过
            log.setAuditId(user.getId());
            log.setAuditTime(new Date());
            log.setNote("审核未通过！");
            //保存审核失败日志
            searchMasterMsgAuditLogMapper.insert(log);
            //设置SearchMasterMsg的信息为驳回状态
            smm.setState(-1);
            smm.setNote("审核未通过！");
        } else {
            //审核通过（不用保存日志）
            //SmsUtil.sendSms(user.getPhone(),"您发布的消息已审核通过，请静候佳音！");
            //设置SearchMasterMsg的信息为审核通过状态
            smm.setState(1);
            smm.setNote("审核通过！");
            //获取当前寻主信息地址坐标
            Point point = DistanceUtil.getPoint(smm.getAddress());
            //查询离当前填写地址50km最近的店铺
            Shop nearestShop = DistanceUtil.getNearestShop(point, shopMapper.selectAll());
            if (nearestShop != null) {
                smm.setShopId(nearestShop.getId());
            }
            //如果不存在，就什么也不操作（寻主池）
        }
        searchMasterMsgMapper.update(smm);
    }

    @Override
    public void accept(AcceptDto dto) {
        //判断是否已经存在待处理订单
        OrderPetAcquisition op = orderPetAcquisitionMapper.selectToHandleOrderByMsgId(dto.getMsgId());
        if(op != null){
            throw new CustomException("已存在待处理收购单！！");
        }
        //根据寻主消息生成宠物基本信息
        SearchMasterMsg smm = searchMasterMsgMapper.selectById(dto.getMsgId());
        Pet pet = initSmm2Pet(smm,dto.getHandler());
        //保存宠物
        petMapper.insert(pet);
        //ctrl+alt+m，单独抽方法,保存收购单
        OrderPetAcquisition opa = initAcquisition(dto, smm, pet);
        orderPetAcquisitionMapper.insert(opa);
    }

    private OrderPetAcquisition initAcquisition(AcceptDto dto, SearchMasterMsg smm, Pet pet) {
        OrderPetAcquisition opa = new OrderPetAcquisition();
        opa.setOrderSn(CodeGenerateUtils.generateOrderSn(dto.getMsgId()));//利用工具类生成订单唯一编号
        opa.setDigest(pet.getName()+"收购计划");
        opa.setLastcomfirmtime(new Date(System.currentTimeMillis()+2*24*60*60*1000));
        opa.setState(0);//待处理
        opa.setPetId(pet.getId());
        opa.setUserId(smm.getUserId());
        opa.setShopId(dto.getHandler().getShopId());
        opa.setAddress(smm.getAddress());
        opa.setEmpId(dto.getHandler().getId());
        opa.setSearchMasterMsgId(smm.getId());
        return opa;
    }

    private Pet initSmm2Pet(SearchMasterMsg smm, Employee handler) {
        Pet pet = new Pet();
        pet.setName(smm.getName());
        pet.setState(0L);//下架
        pet.setCreatetime(new Date());
        pet.setTypeId(smm.getPetType());
        pet.setShopId(handler.getShopId());
        pet.setUserId(smm.getUserId());
        pet.setSearchMasterMsgId(smm.getId());
        return pet;
    }
}
